import {plays, invoices} from "./data.js";
import {createStatement} from "./createStatementDataFinal.js";


// 和第三版对比
// 以多态取代条件表达式

// 对比第三版，以多态取代条件表达式

function statement(invoice, plays) {
  // return renderPlainText(createStatement(invoice, plays));
  document.body.innerHTML = renderHtml(createStatement(invoice, plays))
}

// 将账单数据以普通文本展示
function renderPlainText(statementData) {

  let result = statementData.performances
    .reduce((prev, curr) => prev += `${curr.play.name}: ${usd(curr.amount)} (${curr.audience} seats)\n`,
      `Statement for ${statementData.customer}\n`);

  result += `Amount owed is ${usd(statementData.totalAmount)}\n`;
  result += `You earned ${statementData.totalVolumeCredits} credits \n`;

  return result;

}

function renderHtml(statementData) {

  let result = `<h1>Statement for ${statementData.customer}</h1>\n`;
  result += "<table>\n";
  result += "<tr><th>play</th><th>seats</th><th>cost</th></tr>";


  for (let performance of statementData.performances) {
    result += `<tr><td>${performance.play.name}</td><td>${performance.volumeCredits}</td>`;
    result += `<td>${usd(performance.amount)}</td></tr>`
  }

  result += "</table>\n";
  result += `<p>Amount owed is <em>${usd(statementData.totalAmount)}</em></p>\n`;
  result += `<p>You earned <em>${statementData.totalVolumeCredits}</em> credits</p>\n`;

  return result;

}

// 提炼函数，格式化金额
function usd(amount) {
  return new Intl.NumberFormat("en-US",
    {style: "currency", currency: "USD", minimumFractionDigits: 2}).format(amount / 100);
}

for (let invoice of invoices) {
  let result = statement(invoice, plays);
  console.log(result);
}
